// popup.js
let canvas = document.getElementById("editorCanvas");
let ctx = canvas.getContext("2d");
let isDrawing = false;

// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", function () {
  // 设置canvas初始尺寸
  canvas.width = 500;
  canvas.height = 200;

  // 设置canvas背景为透明（清空画布）
  clearCanvas();

  // 添加边框提示用户签名区域
  drawPlaceholder();

  // 绑定事件监听器
  bindEventListeners();
});

function clearCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function drawPlaceholder() {
  // 添加边框提示用户签名区域
  ctx.strokeStyle = "#e2e8f0";
  ctx.lineWidth = 2;
  ctx.setLineDash([5, 5]);
  ctx.strokeRect(10, 10, canvas.width - 20, canvas.height - 20);
  ctx.setLineDash([]);

  // 添加提示文字
  ctx.fillStyle = "#a0aec0";
  ctx.font = "16px 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
  ctx.textAlign = "center";
  ctx.fillText(
    "在此区域绘制签名或生成文本签名",
    canvas.width / 2,
    canvas.height / 2
  );
}

function bindEventListeners() {
  // 生成签名图片按钮
  document
    .getElementById("generateSignature")
    .addEventListener("click", generateSignatureFromText);

  // 保存签名按钮
  document.getElementById("saveBtn").addEventListener("click", saveSignature);

  // 绘制功能
  canvas.addEventListener("mousedown", startDrawing);
  canvas.addEventListener("mousemove", draw);
  canvas.addEventListener("mouseup", stopDrawing);
  canvas.addEventListener("mouseout", stopDrawing);

  // 触摸设备支持
  canvas.addEventListener("touchstart", handleTouchStart);
  canvas.addEventListener("touchmove", handleTouchMove);
  canvas.addEventListener("touchend", stopDrawing);
}

let lastX = 0;
let lastY = 0;

function startDrawing(e) {
  isDrawing = true;
  [lastX, lastY] = getPosition(e);
}

function draw(e) {
  if (!isDrawing) return;
  e.preventDefault();

  const [x, y] = getPosition(e);

  ctx.beginPath();
  ctx.moveTo(lastX, lastY);
  ctx.lineTo(x, y);
  ctx.strokeStyle = "#000000";
  ctx.lineWidth = 2;
  ctx.lineCap = "round";
  ctx.lineJoin = "round";
  ctx.stroke();

  [lastX, lastY] = [x, y];
}

function stopDrawing() {
  isDrawing = false;
}

function getPosition(e) {
  let x, y;
  if (e.type.includes("touch")) {
    const rect = canvas.getBoundingClientRect();
    x = e.touches[0].clientX - rect.left;
    y = e.touches[0].clientY - rect.top;
  } else {
    const rect = canvas.getBoundingClientRect();
    x = e.clientX - rect.left;
    y = e.clientY - rect.top;
  }
  return [x, y];
}

function handleTouchStart(e) {
  e.preventDefault();
  startDrawing(e.touches[0]);
}

function handleTouchMove(e) {
  e.preventDefault();
  draw(e.touches[0]);
}

// 从文本生成签名
function generateSignatureFromText() {
  const text = document.getElementById("signatureText").value.trim();

  if (!text) {
    alert("请输入签名文本");
    return;
  }

  // 清空canvas，保持透明背景
  clearCanvas();

  // 设置文本样式
  ctx.fillStyle = "#000000";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";

  // 计算合适的字体大小
  let fontSize = 40;
  do {
    ctx.font = `${fontSize}px 'Comic Sans MS', 'Segoe Script', cursive`;
    const textWidth = ctx.measureText(text).width;
    if (textWidth < canvas.width * 0.8) break;
    fontSize -= 2;
  } while (fontSize > 10);

  // 绘制文本
  ctx.font = `${fontSize}px 'Comic Sans MS', 'Segoe Script', cursive`;
  ctx.fillText(text, canvas.width / 2, canvas.height / 2);
}

// 保存签名
function saveSignature() {
  const dataUrl = canvas.toDataURL("image/png");
  const link = document.createElement("a");
  link.download = "signature-" + Date.now() + ".png";
  link.href = dataUrl;
  link.click();
}

// // 接收截图数据（保留原有功能）
// chrome.runtime.onMessage.addListener((message) => {
//   if (message.action === "screenshot_taken") {
//     const img = new Image();
//     img.onload = function () {
//       // 清空现有内容
//       clearCanvas();

//       // 设置canvas尺寸以适应图片
//       const maxWidth = 800;
//       const scale = img.width > maxWidth ? maxWidth / img.width : 1;

//       canvas.width = img.width * scale;
//       canvas.height = img.height * scale;

//       // 绘制图片
//       ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
//     };
//     img.src = message.dataUrl;
//   }
// });
